package com.camera.yl.v

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.util.SparseArray
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.FrameLayout
import android.widget.Spinner
import android.widget.TextView
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.camera.base.bean.CameraMark
import com.camera.base.bean.MarkWaterType
import com.camera.base.util.ToastUtil
import com.camera.base.v.BaseActivity
import com.camera.routemodule.RouterPath
import com.camera.yl.R
import com.camera.yl.databinding.ActivityWatermarkSettingBinding
import com.camera.yl.v.models.WatermarkSettingViewModel
import com.google.android.material.tabs.TabLayout
import dagger.hilt.android.AndroidEntryPoint

@SuppressLint("LongLogTag")
@AndroidEntryPoint
@Route(path = RouterPath.path.watermark_setting_activity)
class WatermarkSettingActivity : BaseActivity<ActivityWatermarkSettingBinding, WatermarkSettingViewModel>() {
    private val TAG = "WatermarkSettingActivity"
    
    // 水印TextView映射，key是水印index，value是对应的TextView
    private val watermarkTextViewMap = SparseArray<TextView>()
    // 水印类型列表
    private val watermarkTypes = listOf(
        "固定自定义",
        "时间",
        "位置",
        "公网账号",
        "国标名称",
        "国标ID",
        "电量",
        "网络类型和信号",
        "自定义类型1",
        "自定义类型2",
        "自定义类型3",
        "自定义类型4",
        "自定义类型5"
    )
    var previewContainerHeight = 0
    override val viewModelClass: Class<WatermarkSettingViewModel>
        get() = WatermarkSettingViewModel::class.java
    
    override fun getLayoutId(): Int {
        return R.layout.activity_watermark_setting
    }
    
    override fun getStatusBarColor(): Int {
        return R.color.title_background_color
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 设置布局比例
        val params = mBinding.previewContainer.layoutParams
        val displayMetrics = resources.displayMetrics
        val width = displayMetrics.widthPixels
        params.height = (width * 9) / 16 // 16:9比例
        previewContainerHeight = params.height
        mBinding.previewContainer.layoutParams = params
    }
    
    override fun initView() {
        // 设置TabLayout
        setupTabLayout()
        
        // 设置位置选择器
        setupPositionSelector()
        
        // 设置文本编辑监听
        setupTextWatcher()
        
        // 设置水印类型选择器
        setupWatermarkTypeSpinner()
    }
    
    /**
     * 设置水印类型选择器
     */
    private fun setupWatermarkTypeSpinner() {
        val spinner: Spinner = mBinding.spinnerWatermarkType
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, watermarkTypes)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinner.adapter = adapter
        
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                val currentWatermark = viewModel.currentWatermark.value ?: return
                
                // 更新水印类型
                currentWatermark.type = position
                
                // 更新UI可见性
                mBinding.layoutWatermarkContent.visibility = if (position == 0) View.VISIBLE else View.GONE
                
                // 如果不是自定义类型，清空content
                if (position != 0) {
                    currentWatermark.content = ""
                }
                
                // 更新预览显示的水印文本
                updateWatermarkDisplayText(currentWatermark)
            }
            
            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        
        // 当前水印类型变化时，更新选择器
        viewModel.currentWatermark.observe(this, Observer { watermark ->
            val type = watermark.type.coerceIn(0, watermarkTypes.size - 1)
            if (spinner.selectedItemPosition != type) {
                spinner.setSelection(type)
            }
            
            // 更新文本框可见性
            mBinding.layoutWatermarkContent.visibility = if (type == 0) View.VISIBLE else View.GONE
            
            // 更新预览显示的水印文本
            updateWatermarkDisplayText(watermark)
        })
    }
    
    /**
     * 更新水印显示文本内容
     * 根据水印类型显示不同的内容
     */
    private fun updateWatermarkDisplayText(watermark: CameraMark) {
        val textView = watermarkTextViewMap[watermark.index] ?: return
        val displayText = when (watermark.type) {
            MarkWaterType.CUNSTOM_FIXED -> {
                // 自定义内容
                if (watermark.content.isNullOrEmpty()) "水印${watermark.index}" else watermark.content
            }
            MarkWaterType.TIME -> "2023-06-18 15:30:00" // 时间示例
            MarkWaterType.LOCATION -> "39.9042° N, 116.4074° E" // 经纬度示例
            MarkWaterType.ACCOUT -> "admin" // 账号示例
            MarkWaterType.GB_NAME -> "DEVICE_NAME" // 国标名称示例
            MarkWaterType.GB_ID -> "DEVICE_ID" // 国标ID
            MarkWaterType.BATTERY -> "电量: 85%" // 电量
            MarkWaterType.NET_TYPE_SINGLE -> "WIFI -1dbm up/down 30.1 KB/S 40.1 KB/S" // 网络类型和信号
            MarkWaterType.CUNSTOM_1 -> "自定义类型1"
            MarkWaterType.CUNSTOM_2 -> "自定义类型2"
            MarkWaterType.CUNSTOM_3 -> "自定义类型3"
            MarkWaterType.CUNSTOM_4 -> "自定义类型4"
            MarkWaterType.CUNSTOM_5 -> "自定义类型5"
            else -> "水印${watermark.index}"
        }
        
        textView.text = displayText
    }
    
    override fun loadData() {
        mBinding.viewModel = viewModel

        // 观察水印列表变化
        viewModel.watermarkList.observe(this, Observer { watermarkList ->
            // 清空所有Tab
            mBinding.tabLayout.removeAllTabs()
            
            // 添加水印Tab
            watermarkList.forEach { watermark ->
                val tab = mBinding.tabLayout.newTab()
                tab.text = "水印" + watermark.index
                tab.tag = watermark.index
                mBinding.tabLayout.addTab(tab)
            }
            
            // 添加"添加"Tab
            val addTab = mBinding.tabLayout.newTab()
            addTab.text = getString(R.string.watermark_add)
            addTab.tag = -1
            mBinding.tabLayout.addTab(addTab)
            
            // 更新水印预览
            updateWatermarkPreview(watermarkList)
            
            // 为新添加的Tab设置长按监听器
            setupLongClickListenersForTabs()
        })

        // 观察当前选中水印变化
        viewModel.currentWatermark.observe(this, Observer { watermark ->
            // 选中对应的Tab
            for (i in 0 until mBinding.tabLayout.tabCount) {
                val tab = mBinding.tabLayout.getTabAt(i)
                if (tab?.tag == watermark.index) {
                    if (tab.isSelected.not()) {
                        tab.select()
                    }
                    break
                }
            }
            
            // 高亮显示当前水印
            highlightCurrentWatermark(watermark.index)
            
            // 更新水印文本内容
            updateCurrentWatermarkText(watermark)
        })
        
        // 观察字体大小变化
        viewModel.fontSize.observe(this, Observer { fontSize ->
            // 只更新当前水印的字体大小
            updateCurrentWatermarkFontSize(fontSize)
        })
        
        // 观察边距变化
        viewModel.leftMargin.observe(this, Observer { margin ->
            // 只更新当前水印的位置
            updateCurrentWatermarkPosition()
        })
        viewModel.rightMargin.observe(this, Observer { margin ->
            // 只更新当前水印的位置
            updateCurrentWatermarkPosition()
        })
        viewModel.topMargin.observe(this, Observer { margin ->
            // 只更新当前水印的位置
            updateCurrentWatermarkPosition()
        })
        viewModel.downMargin.observe(this, Observer { margin ->
            // 只更新当前水印的位置
            updateCurrentWatermarkPosition()
        })
    }
    
    /**
     * 设置TabLayout
     */
    private fun setupTabLayout() {
        mBinding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                val tabId = tab?.tag as? Int ?: return
                
                if (tabId == -1) {
                    // 点击"添加"Tab
                    viewModel.addWatermark()
                } else {
                    // 选中水印
                    viewModel.selectWatermark(tabId)
                }
            }
            
            override fun onTabUnselected(tab: TabLayout.Tab?) {}
            
            override fun onTabReselected(tab: TabLayout.Tab?) {
                // 如果重复点击"添加"Tab
                val tabId = tab?.tag as? Int ?: return
                if (tabId == -1) {
                    viewModel.addWatermark()
                }
            }
        })

        // 初始化时不需要设置长按监听，因为TabLayout中还没有Tab
    }
    
    /**
     * 为所有水印Tab设置长按监听器
     */
    private fun setupLongClickListenersForTabs() {
        for (i in 0 until mBinding.tabLayout.tabCount) {
            val tab = mBinding.tabLayout.getTabAt(i)
            val tabId = tab?.tag as? Int ?: continue
            
            // 只为水印Tab添加长按事件，不为"添加"Tab添加
            if (tabId != -1) {
                tab.view.setOnLongClickListener {
                    // 显示确认删除对话框
                    showDeleteWatermarkDialog(tabId)
                    true
                }
            }
        }
    }
    
    /**
     * 显示确认删除水印的对话框
     */
    private fun showDeleteWatermarkDialog(watermarkId: Int) {
        // 判断是否只剩下一个水印
        if (viewModel.watermarkList.value?.size ?: 0 <= 1) {
            ToastUtil.showLong("至少需要保留一个水印")
            return
        }
        
        showSureDialog(
            "是否删除水印${watermarkId}？",
            onCancel = {
                // 取消操作，不做任何事
            },
            onConfirm = {
                // 确认删除
                viewModel.deleteWatermark(watermarkId)
            }
        )
    }
    
    /**
     * 设置位置选择器
     */
    private fun setupPositionSelector() {
        mBinding.rgPosition.setOnCheckedChangeListener { group, checkedId ->
            val position = when (checkedId) {
                R.id.rb_position_1 -> 1
                R.id.rb_position_2 -> 2
                R.id.rb_position_3 -> 3
                R.id.rb_position_4 -> 4
                else -> 1
            }
            
            // 更新TextView位置
            updateCurrentWatermarkPosition(position)
        }
    }
    
    /**
     * 设置文本编辑监听
     */
    private fun setupTextWatcher() {
        // 监听水印文本变化，立即更新预览
        mBinding.etWatermarkText.addTextChangedListener(object : android.text.TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            
            override fun afterTextChanged(s: android.text.Editable?) {
                // 更新当前水印文本内容
                s?.toString()?.let { text ->
                    viewModel.updateCurrentWatermarkText(text)
                    
                    // 更新TextView显示
                    viewModel.currentWatermark.value?.let { watermark ->
                        updateCurrentWatermarkText(watermark)
                    }
                }
            }
        })
    }
    
    /**
     * 更新水印预览
     */
    private fun updateWatermarkPreview(watermarkList: List<CameraMark>) {
        // 如果预览容器尺寸为0，等待布局完成后再添加水印
        if (mBinding.previewContainer.width == 0 || mBinding.previewContainer.height == 0) {
            mBinding.previewContainer.post {
                refreshWatermarkTextViews(watermarkList)
            }
        } else {
            refreshWatermarkTextViews(watermarkList)
        }
        
        // 更新后重新设置长按监听器
        setupLongClickListenersForTabs()
    }
    
    /**
     * 刷新所有水印TextView
     * 这个方法会比较现有的TextView和水印列表，添加新的、删除旧的，确保一一对应
     */
    private fun refreshWatermarkTextViews(watermarkList: List<CameraMark>) {
        val containerWidth = mBinding.previewContainer.width
        val containerHeight = mBinding.previewContainer.height
        
        // 记录当前水印ID列表，用于检查需要删除的TextView
        val currentWatermarkIds = watermarkList.map { it.index }.toSet()
        val idsToRemove = mutableListOf<Int>()
        
        // 检查需要删除的TextView
        for (i in 0 until watermarkTextViewMap.size()) {
            val watermarkId = watermarkTextViewMap.keyAt(i)
            if (!currentWatermarkIds.contains(watermarkId)) {
                idsToRemove.add(watermarkId)
            }
        }
        
        // 删除不需要的TextView
        idsToRemove.forEach { id ->
            val textView = watermarkTextViewMap[id]
            mBinding.previewContainer.removeView(textView)
            watermarkTextViewMap.remove(id)
        }

        // 处理每个水印
        watermarkList.forEach { watermark ->
            // 检查是否已存在对应的TextView
            var watermarkTextView = watermarkTextViewMap[watermark.index]
            if (watermarkTextView == null) {
                // 创建新的TextView
                watermarkTextView = TextView(this)
                watermarkTextView.tag = watermark.index
                watermarkTextView.setTextColor(Color.WHITE)
                // 根据类型设置显示文本

                watermarkTextView.textSize = watermark.size * 100 * previewContainerHeight / 1080

                // 创建布局参数
                val layoutParams = createWatermarkLayoutParams(watermark, containerWidth, containerHeight)
                
                // 添加TextView到预览容器
                watermarkTextView.layoutParams = layoutParams
                mBinding.previewContainer.addView(watermarkTextView)
                // 保存到映射
                watermarkTextViewMap.put(watermark.index, watermarkTextView)
                updateWatermarkDisplayText(watermark)
            } else {
                // 更新现有TextView
                // 根据类型设置显示文本

                watermarkTextView.textSize = watermark.size * 100 * previewContainerHeight / 1080
                val layoutParams = createWatermarkLayoutParams(watermark, containerWidth, containerHeight)
                watermarkTextView.layoutParams = layoutParams
                updateWatermarkDisplayText(watermark)
            }
        }
        
        // 高亮显示当前选中的水印
        viewModel.currentWatermark.value?.let { currentWatermark ->
            highlightCurrentWatermark(currentWatermark.index)
        }
    }
    
    /**
     * 为水印创建布局参数
     */
    private fun createWatermarkLayoutParams(watermark: CameraMark, containerWidth: Int, containerHeight: Int): FrameLayout.LayoutParams {
        val layoutParams = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        
        // 确保position值是1-4之间
        val position = if (watermark.position in 1..4) watermark.position else 1
        when (position) {
            1 -> { // 左上角
                layoutParams.gravity = Gravity.TOP or Gravity.START
                layoutParams.topMargin = (containerHeight * watermark.top_margin).toInt()
                layoutParams.leftMargin = (containerWidth * watermark.left_margin).toInt()
            }
            2 -> { // 右上角
                layoutParams.gravity = Gravity.TOP or Gravity.END
                layoutParams.topMargin = (containerHeight * watermark.top_margin).toInt()
                layoutParams.rightMargin = (containerWidth * watermark.right_margin).toInt()
            }
            3 -> { // 左下角
                layoutParams.gravity = Gravity.BOTTOM or Gravity.START
                layoutParams.bottomMargin = (containerHeight * watermark.bottom_margin).toInt()
                layoutParams.leftMargin = (containerWidth * watermark.left_margin).toInt()
            }
            4 -> { // 右下角
                layoutParams.gravity = Gravity.BOTTOM or Gravity.END
                layoutParams.bottomMargin = (containerHeight * watermark.bottom_margin).toInt()
                layoutParams.rightMargin = (containerWidth * watermark.right_margin).toInt()
            }
        }
        
        return layoutParams
    }
    
    /**
     * 高亮显示当前选中的水印
     */
    private fun highlightCurrentWatermark(currentId: Int) {
        // 遍历所有水印TextView，设置高亮或取消高亮
        for (i in 0 until watermarkTextViewMap.size()) {
            val watermarkId = watermarkTextViewMap.keyAt(i)
            val textView = watermarkTextViewMap.valueAt(i)
            
            if (watermarkId == currentId) {
                // 高亮当前选中的水印
                textView.setBackgroundColor(Color.parseColor("#33FFFFFF"))
            } else {
                // 取消高亮其他水印
                textView.setBackgroundColor(Color.TRANSPARENT)
            }
        }
    }
    
    /**
     * 更新当前水印的位置
     */
    private fun updateCurrentWatermarkPosition(position : Int? = null) {

        val currentWatermark = viewModel.currentWatermark.value ?: return
        val textView = watermarkTextViewMap[currentWatermark.index] ?: return
        val containerWidth = mBinding.previewContainer.width
        val containerHeight = mBinding.previewContainer.height
        position?.let {
            currentWatermark.position = it
        }
        Log.e(TAG, "updateCurrentWatermarkPosition: "+viewModel.leftMargin.value )
        currentWatermark.left_margin = viewModel.leftMargin.value!!.toFloat() / 100
        currentWatermark.right_margin = viewModel.rightMargin.value!!.toFloat() / 100
        currentWatermark.top_margin = viewModel.topMargin.value!!.toFloat() / 100
        currentWatermark.bottom_margin = viewModel.downMargin.value!!.toFloat() / 100
        // 创建新的布局参数
        val layoutParams = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        
        // 当前水印的position值
        val positionValue = if (currentWatermark.position in 1..4) currentWatermark.position else 1
        
        when (positionValue) {
            1 -> { // 左上角
                layoutParams.gravity = Gravity.TOP or Gravity.START
                layoutParams.topMargin = (containerHeight * (viewModel.topMargin.value ?: 10) / 100f).toInt()
                layoutParams.leftMargin = (containerWidth * (viewModel.leftMargin.value ?: 10) / 100f).toInt()
            }
            2 -> { // 右上角
                layoutParams.gravity = Gravity.TOP or Gravity.END
                layoutParams.topMargin = (containerHeight * (viewModel.topMargin.value ?: 10) / 100f).toInt()
                layoutParams.rightMargin = (containerWidth * (viewModel.rightMargin.value ?: 10) / 100f).toInt()
            }
            3 -> { // 左下角
                layoutParams.gravity = Gravity.BOTTOM or Gravity.START
                layoutParams.bottomMargin = (containerHeight * (viewModel.downMargin.value ?: 10) / 100f).toInt()
                layoutParams.leftMargin = (containerWidth * (viewModel.leftMargin.value ?: 10) / 100f).toInt()
            }
            4 -> { // 右下角
                layoutParams.gravity = Gravity.BOTTOM or Gravity.END
                layoutParams.bottomMargin = (containerHeight * (viewModel.downMargin.value ?: 10) / 100f).toInt()
                layoutParams.rightMargin = (containerWidth * (viewModel.rightMargin.value ?: 10) / 100f).toInt()
            }
        }
        
        // 更新TextView的布局参数
        textView.layoutParams = layoutParams
    }
    
    /**
     * 更新当前水印的字体大小
     */
    private fun updateCurrentWatermarkFontSize(fontSize: Int) {
        val currentWatermark = viewModel.currentWatermark.value ?: return
        val textView = watermarkTextViewMap[currentWatermark.index] ?: return
        Log.e(TAG, "updateCurrentWatermarkFontSize: "+fontSize )
        // 更新字体大小
        textView.textSize = fontSize * previewContainerHeight / 1080f
        // 更新当前水印对象中的size值
        currentWatermark.size = fontSize / 100f
    }
    
    /**
     * 更新当前水印的文本内容
     */
    private fun updateCurrentWatermarkText(watermark: CameraMark) {
        val textView = watermarkTextViewMap[watermark.index] ?: return
        
        // 更新显示文本
        updateWatermarkDisplayText(watermark)
    }
} 